<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :xs="12" :sm="12">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <!-- 年度选择器：保持change事件监听 -->
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择年度"
                @change="handleYearChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="体检表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table :ref="refKeys[0]" :loading="cwHealthFormTable.loading" :columns="cwHealthFormTable.columns"
          :dataSource="cwHealthFormTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
          :rowSelection="true" :actionButton="true" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
// 1. 引入JeecgBoot内置的request工具（框架通用请求方式）
import { getAction } from '@/api/manage'

export default {
  name: 'CwTjForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: { xs: { span: 24 }, sm: { span: 5 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
      model: { year: '' }, // 初始为空，由watch同步全局年度
      validatorRules: {
        unit: [{ required: true, message: '请选择单位!' }],
        year: [{ required: true, message: '请选择年度!' }],
      },
      addDefaultRowNum: 1,
      refKeys: ['cwHealthForm'],
      tableKeys: ['cwHealthForm'],
      activeKey: 'cwHealthForm',
      confirmLoading: false, // 主表单加载状态
      // 体检表配置（保持不变）
      cwHealthFormTable: {
        loading: false, // 子表加载状态
        dataSource: [],
        columns: [
          // {
          //   title: '财政/非财政',
          //   key: 'czFcz',
          //   type: FormTypes.select,
          //   dictCode: "cz_fcz",
          //   width: "200px",
          //   placeholder: '请输入${title}',
          //   defaultValue: '',
          // },
          {
            title: '姓名',
            key: 'name',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '在职、退休',
            key: 'zzTx',
            type: FormTypes.select,
            dictCode: "zz_tx",
            width: "200px",
            placeholder: '请选择${title}',
            defaultValue: '',
          },
          {
            title: '性别',
            key: 'gender',
            type: FormTypes.select,
            dictCode: "gender",
            width: "200px",
            placeholder: '请选择${title}',
            defaultValue: '',
          },
          {
            title: '金额(万元)',
            key: 'money',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
        ]
      },
      // API地址配置（保持JeecgBoot规范，无需修改）
      url: {
        add: "/cw/cwTj/add",
        edit: "/cw/cwTj/edit",
        cwHealthForm: { list: '/cw/cwTj/queryCwHealthFormByMainId' },
        getByYear: '/cw/cwTj/list' // 年度查询接口（GET请求）
      },
      isManualChange: false // 标记是否手动修改过表单年度
    }
  },
  props: {
    disabled: { type: Boolean, default: false, required: false },
    scene: { // 接收 Modal 传递的场景值
      type: String,
      default: ''
    }
  },

  computed: {
    formDisabled() { return this.disabled },
    ...mapState({ globalYear: state => state.app.globalYear })
  },
  watch: {
    // 监听全局年度变化，同步到表单（仅当未手动修改时）
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
        // 可选：自动触发年度查询，解开注释即可
        // this.handleYearChange(newVal)
      }
    },
    // 监听表单年度变化，标记是否手动修改
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true // 手动修改后，不再同步全局年度
      }
    }
  },

  created() {
    // 初始化时同步全局年度
    this.model.year = this.globalYear
    const scene = this.scene; // 接收 Modal 传递的 scene（add/edit）
    this.currentScene = scene; // 存储到本地变量，后续复用
    console.log(scene)
    if (scene=='add'){
      this. handleYearChange(this.model.year)
    }

  },
  methods: {
    addBefore() { this.cwHealthFormTable.dataSource = [] },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    editAfter() {
      this.$nextTick(() => { })
      if (this.model.id) {
        let params = { id: this.model.id }
        // 子表查询也适配JeecgBoot的getAction（原逻辑可能已兼容，此处统一规范）
        getAction(this.url.cwHealthForm.list, params).then(res => {
          if (res.success) {
            this.cwHealthFormTable.dataSource = res.result.records || []
          }
        }).finally(() => {
          this.cwHealthFormTable.loading = false
        })
      }
    },
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => resolve(allValues)).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else { console.error(e) }
        })
      })
    },
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return { ...main, cwHealthFormList: allValues.tablesValue[0].values }
    },
    validateError(msg) { this.$message.error(msg) },
    close() {
      this.visible = false
      this.$emit('close')
      // 兼容JeecgBoot表单清空验证逻辑
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },

    async handleYearChange(year) {
      // 清空逻辑：未选择年度时，保留单位，清空其他数据
      if (!year) {
        this.model = { unit: this.model.unit }
        this.cwHealthFormTable.dataSource = []
        return
      }

      // 加载状态：主表+子表同时加载
      this.confirmLoading = true
      this.cwHealthFormTable.loading = true

      try {
        // 1. 调用年度查询接口
        const yearResponse = await getAction(this.url.getByYear, { year })

        if (yearResponse.success && yearResponse.result.records.length > 0) {
          const mainRecord = yearResponse.result.records[0]
          // 主表数据回显：保留用户已选的unit和year，合并接口返回的其他字段
          this.model = {
            ...this.model,
            ...mainRecord
          }
          console.log(mainRecord, "54545645645");


          // 2. 使用返回的mainId调用体检表列表接口
          if (mainRecord.id) {
            const healthResponse = await getAction(this.url.cwHealthForm.list, {
              id: mainRecord.id
            })

            if (healthResponse.success) {
              this.cwHealthFormTable.dataSource = healthResponse.result.records || []
            } else {
              this.$message.warning('获取体检表数据失败：' + (healthResponse.message || '未知错误'))
              this.cwHealthFormTable.dataSource = []
            }
          } else {
            this.$message.warning('未获取到体检表关联ID，无法加载体检数据')
            this.cwHealthFormTable.dataSource = []
          }
        } else {
          // 接口返回失败（如无数据），显示警告并清空子表
          this.$message.warning(yearResponse.message || '该年度暂无数据')
          this.cwHealthFormTable.dataSource = []
          this.model.id = undefined;

        }
      } catch (error) {
        // 异常处理
        console.error('查询接口异常：', error)
        this.$message.error('查询失败，请刷新页面重试或联系管理员')
        this.cwHealthFormTable.dataSource = []
      } finally {
        // 关闭加载状态（无论成功/失败）
        this.confirmLoading = false
        this.cwHealthFormTable.loading = false
      }
    }
  }
}
</script>

<style scoped></style>